<template>
  <div class="cont-wrap">
    <div class="crumbs-wrap" style="margin-top: 50px">
      <div class="lf">
        <router-link to="../../manage/device">设备管理</router-link>
        <svg-icon iconClass="right-jiantou"></svg-icon>
        <router-link to="../../../../manage/device">{{ name }}</router-link>
        <svg-icon iconClass="right-jiantou"></svg-icon>
        <span>端口流量</span>
      </div>
      <div class="rt">
        <button :disabled="disabled" @click="collect">汇总流量</button>
      </div>
    </div>
    <div class="diagram-wrap">
      <div class="item" v-for="(item, index) in chartData" :key="index">
        <vxe-checkbox
          v-model="item.checked"
          @change="checkboxChange(item)"
          content=""
        ></vxe-checkbox>
        <div class="head">
          <el-tooltip
            class="ip"
            effect="dark"
            :content="item.ip"
            placement="bottom"
          >
            <p><span>IP:</span>
            {{ item.ip }}</p>
          </el-tooltip>
          <el-tooltip
            class="port"
            effect="dark"
            :content="item.name"
            placement="bottom"
          >
            <p><span>端口号:</span>
            {{ item.name }}</p>
          </el-tooltip>
          <div class="date">
            <el-date-picker
              v-model="item.timeSection"
              type="datetimerange"
              range-separator="~"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="mini"
              @change="dateChange(item, $event)"
            >
            </el-date-picker>
          </div>
        </div>
        <!-- <div class="h1">1242M</div> -->
        <ve-line
          class="diagram"
          :data="item"
          :settings="chartSettings"
          width="100%"
          height="330px"
        ></ve-line>
      </div>
    </div>
    <!-- 汇总弹窗 -->
    <div
      class="collect-wrap"
      v-if="isShowCollect && collectChartData.rows.length > 0"
    >
      <div class="close-btn" @click="closeCollectWrap">
        <svg-icon icon-class="close"></svg-icon>
      </div>
      <ve-line
        class="diagram"
        :data="collectChartData"
        :settings="chartSettings"
        width="870px"
        height="370px"
      ></ve-line>
      <div class="confirm-btn" @click="closeCollectWrap">确定</div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { getInterface } from "@/api/manage";

@Component
export default class diagram extends Vue {
  public name: String = "";
  public port: String = "";
  public chartSettings: Object = {
    area: false,
    itemStyle: {
      // color: "#49A9EE",
    },
  };

  public chartData: Object[] = [
    // {
    //   checked: false,
    //   date: "",
    //   columns: ["日期", "端口流量"],
    //   rows: [
    //     { 日期: "3-1", 端口流量: 30 },
    //     { 日期: "3-2", 端口流量: 20 },
    //     { 日期: "3-3", 端口流量: 35 },
    //     { 日期: "3-4", 端口流量: 62 },
    //     { 日期: "3-5", 端口流量: 44 },
    //     { 日期: "3-6", 端口流量: 12 },
    //   ],
    // },
    // {
    //   checked: false,
    //   date: "",
    //   columns: ["日期", "端口流量"],
    //   rows: [
    //     { 日期: "4-1", 端口流量: 10 },
    //     { 日期: "4-2", 端口流量: 22 },
    //     { 日期: "4-3", 端口流量: 8 },
    //     { 日期: "4-4", 端口流量: 90 },
    //     { 日期: "4-5", 端口流量: 32 },
    //     { 日期: "4-6", 端口流量: 40 },
    //   ],
    // },
    // {
    //   checked: false,
    //   date: "",
    //   columns: ["日期", "端口流量"],
    //   rows: [
    //     { 日期: "5-1", 端口流量: 88 },
    //     { 日期: "5-2", 端口流量: 75 },
    //     { 日期: "5-4", 端口流量: 64 },
    //     { 日期: "5-5", 端口流量: 58 },
    //     { 日期: "5-6", 端口流量: 29 },
    //   ],
    // },
  ];

  public collectSelect: Object[] = []; //汇总流量选中
  public collectChartData: Object[] = []; //汇总流量数据-图表
  public disabled: Boolean = true;
  public isShowCollect: Boolean = false;
  $route: any;

  public created() {
    let date = Math.round(new Date() / 1000) - 1800;
    let fromtime = this.ormatDate(date);
    // console.log("date", date);
    // console.log("date", _date);
    // console.log(this.$route.params.ip);
    this.name = this.$route.params.name;
    console.log('name',this.$route.params.name);
    
    let port = this.$route.params.port;
    let portarray = eval("(" + port + ")"); //端口号
    let _portarray = portarray.join(",");
    // console.log("portarray", portarray);
    // console.log("_portarray", _portarray);
    // 获取端口信息
    this.getPortInfo(this.$route.params.ip, _portarray, fromtime, "");
  }

  // 汇总流量
  public collect() {
    // console.log(this.chartData);
    // console.log(this.collectSelect);
    if (this.collectSelect.length <= 1) {
      this.$message({
        showClose: true,
        message: "至少勾选两个！",
        type: "error",
      });
    } else {
      let final = [];
      for (let i = 0; i < this.collectSelect.length; i++) {
        for (let j = 0; j < this.collectSelect[i].rows.length; j++) {
          let row = this.collectSelect[i].rows[j];
          if (final.hasOwnProperty(row.time)) {
            let temp = final[row.time];
            temp.日期 = row.time;
            // temp.inputByteSpeed += parseInt(row.inputByteSpeed);
            temp.输入效率 = temp.inputByteSpeed + parseInt(row.inputByteSpeed);
            // temp.outputByteSpeed += parseInt(row.outputByteSpeed);
            temp.输出效率 =
              temp.outputByteSpeed + parseInt(row.outputByteSpeed);
          } else {
            final[row.time] = {
              time: row.time,
              日期: row.time,
              inputByteSpeed: parseInt(row.inputByteSpeed),
              输入效率: parseInt(row.inputByteSpeed),
              outputByteSpeed: parseInt(row.outputByteSpeed),
              输出效率: parseInt(row.outputByteSpeed),
            };
          }
        }
      }
      let collectChartData = [];
      collectChartData.columns = ["日期", "输入效率", "输出效率"];

      // console.log('final',final)
      let rows = [];
      for (const key in final) {
        if (Object.prototype.hasOwnProperty.call(final, key)) {
          // console.log(final[key])
          rows.push(final[key]);
          collectChartData.rows = rows;
        }
      }
      this.collectChartData = collectChartData;
      // console.log(
      //   "this.collectChartData",
      //   this.collectChartData
      // );
      this.isShowCollect = true;
    }
  }

  // 关闭汇总流量弹窗
  public closeCollectWrap() {
    this.isShowCollect = false;
  }

  // 复选
  public checkboxChange(item: Object) {
    // console.log(item)
    // console.log(this.chartData)
    for (const i in this.chartData) {
      if (Object.prototype.hasOwnProperty.call(this.chartData, i)) {
        const element = this.chartData[i];
        if (element.checked == true) {
          this.disabled = false;
          break;
        } else {
          this.disabled = true;
        }
      }
    }
    if (item.checked) {
      this.collectSelect.push(item);
    } else {
      this.collectSelect = this.collectSelect.filter((items, i) => {
        return items.name != item.name;
      });
    }
  }

  // 获取端口信息
  public getPortInfo(ip: any, interfacename: any, fromtime: string, totime: string) {
    if (totime == "") {
      // console.time("耗时");
      getInterface({
        ip: ip,
        fromtime: fromtime,
        interfacename: interfacename,
      }).then((res) => {
        res.data.reverse();
        console.log("获取端口信息", res.data);
        
        let tempArr = [];
        let data = [];
        for (let i = 0; i < res.data.length; i++) {
          res.data[i]["输入速率"] = res.data[i].inputByteSpeed;
          res.data[i]["输出速率"] = res.data[i].outputByteSpeed;
          res.data[i]["日期"] = res.data[i].time;
          res.data[i].timeSection = [];
          if (tempArr.indexOf(res.data[i].name) === -1) {
            data.push({
              name: res.data[i].name,
              checked: false,
              date: "",
              ip: res.data[i].ip,
              columns: ["日期", "输入速率", "输出速率"],
              rows: [res.data[i]],
            });
            tempArr.push(res.data[i].name);
          } else {
            for (let j = 0; j < data.length; j++) {
              if (data[j].name == res.data[i].name) {
                data[j].rows.push(res.data[i]);
                break;
              }
            }
          }
        }
        // console.log("流量", data);
        this.chartData = data;

        // console.timeEnd("耗时");
      });
    } else {
      // 日期筛选
      // console.log("日期筛选");
      // console.time("耗时");
      getInterface({
        ip: ip,
        fromtime: fromtime,
        interfacename: interfacename,
        totime: totime,
      }).then((res) => {
        // console.log("日期筛选", res.data);
        // console.log(interfacename);
        // console.log(this.chartData);
        res.data.reverse();
        if (res.data == "") {
          this.$message({
            showClose: true,
            message: "数据为空！",
            type: "error",
          });
        } else {
          let tempArr = [];
          let data = [];
          for (let i = 0; i < res.data.length; i++) {
            res.data[i]["输入速率"] = res.data[i].inputByteSpeed;
            res.data[i]["输出速率"] = res.data[i].outputByteSpeed;
            res.data[i]["日期"] = res.data[i].time;
            res.data[i].timeSection = [];
            if (tempArr.indexOf(res.data[i].name) === -1) {
              data.push({
                name: res.data[i].name,
                checked: false,
                date: "",
                ip: res.data[i].ip,
                columns: ["日期", "输入速率", "输出速率"],
                rows: [res.data[i]],
              });
              tempArr.push(res.data[i].name);
            } else {
              for (let j = 0; j < data.length; j++) {
                if (data[j].name == res.data[i].name) {
                  data[j].rows.push(res.data[i]);
                  break;
                }
              }
            }
          }
          // console.log("///", data);

          for (let i = 0; i < this.chartData.length; i++) {
            if (this.chartData[i].name == interfacename) {
              // console.log(this.chartData[i]);
              this.chartData[i].rows = data[0].rows;
            }
          }
          // console.log("---", this.chartData);
          // console.timeEnd("耗时");
        }
      });
    }
  }

  //日期选择
  public dateChange(item: { name: any; }, $event: any[]) {
    // console.log("dateChange", item.name, item.ip);
    // console.log("item", item);
    // console.log($event);
    // console.log(this.time($event[0]));
    // console.log(this.time($event[1]));
    if (this.time($event[0]) == this.time($event[1])) {
      this.$message({
        showClose: true,
        message: "开始时间和结束时间不能相同！",
        type: "error",
      });
    } else {
      // 获取端口信息
      this.getPortInfo(
        this.$route.params.ip,
        item.name,
        this.time($event[0]),
        this.time($event[1])
      );
    }
  }

  // 时间戳转换
  public ormatDate(dateNum: number) {
    var date = new Date(dateNum * 1000);
    return (
      date.getFullYear() +
      "-" +
      fixZero(date.getMonth() + 1, 2) +
      "-" +
      fixZero(date.getDate(), 2) +
      " " +
      fixZero(date.getHours(), 2) +
      ":" +
      fixZero(date.getMinutes(), 2) +
      ":" +
      fixZero(date.getSeconds(), 2)
    );
    function fixZero(num: string|number, length: number) {
      var str = "" + num;
      var len = str.length;
      var s = "";
      for (var i = length; i-- > len; ) {
        s += "0";
      }
      return s + str;
    }
  }

  //中国标准时间转换为yymmdd
  public time(date: { getFullYear: () => any; getMonth: () => number; getDate: () => any; getHours: () => any; getMinutes: () => any; getSeconds: () => any; }) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? "0" + m : m;
    var d = date.getDate();
    d = d < 10 ? "0" + d : d;
    var h = date.getHours();
    h = h < 10 ? "0" + h : h;
    var minute = date.getMinutes();
    minute = minute < 10 ? "0" + minute : minute;
    var second = date.getSeconds();
    second = second < 10 ? "0" + second : second;
    return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
.cont-wrap
  width 1315px
  margin 0 auto
  .crumbs-wrap
    display flex
    justify-content space-between
    align-items center
    height 30px
    .lf
      font-size 13px
      color #333
      display flex
      align-items center
      .svg-icon
        width 5px
        height 6px
        margin 0 12px
      span
        color #000
        font-weight 700
    .rt
      button
        width 123px
        height 30px
        background #1269ff
        color #fff
        border-radius 4px
        outline none
        border none
        font-size 13px
        font-style oblique
        cursor pointer
      button:disabled
        background #c1c1c1
        font-style normal
        cursor default
  .diagram-wrap
    display flex
    justify-content space-between
    flex-wrap wrap
    margin-top 30px
    .item
      border solid 1px #EBEBEB
      border-radius 4px
      background #fff
      margin-bottom 45px
      padding 0 30px
      padding-top 25px
      position relative
      width 48%
      /deep/.vxe-checkbox
        position absolute
        right 5px
        top 8px
      .head
        display flex
        justify-content space-between
        align-items center
        font-size 13px
        color rgba(49, 49, 49, 0.847058823529412)
        padding 0 25px
        .ip
          width 110px
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
          span
            font-weight 700
        .port
          width 200px
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
          span
            font-weight 700
        .date
          width 222px
          height 28px
          /deep/.el-date-editor--datetimerange.el-input__inner
            width 100%
            border-radius 6px
          /deep/.el-date-editor .el-range-separator
            width auto
          /deep/.el-date-editor .el-range-input
            width 32%
      .h1
        font-size 24px
        font-weight 700
        color #2854CA
        padding 0 25px
.collect-wrap
  position fixed
  left 0
  right 0
  top 180px
  margin 0 auto
  z-index 10005
  width 960px
  // height 500px
  background #fff
  border solid 8px rgba(170, 170, 170, 0.1)
  padding 10px 40px
  border-radius 10px
  .close-btn
    position absolute
    top 18px
    right 18px
    cursor pointer
  .confirm-btn
    width 134px
    height 30px
    line-height 30px
    text-align center
    background #1269ff
    color #fff
    font-size 13px
    border-radius 4px
    margin 10px auto
    cursor pointer
</style>